package eva.savant.business.contabilidad.view

import eva.savant.core.view.Maestro
import eva.savant.businessobject.cg.Cuenta

import org.primefaces.model.TreeNode
import org.primefaces.event.NodeSelectEvent
import org.primefaces.model.DefaultTreeNode
import javax.faces.bean.ManagedBean
import javax.faces.bean.SessionScoped
import javax.annotation.PostConstruct
import javax.faces.convert.Converter

@SessionScoped
@ManagedBean(name = 'IMCuenta')
public class IMCuenta extends Maestro {

  TreeNode root, selectedNode

  def list

  @PostConstruct
  public void cleanEntity() {

    entity= new Cuenta(); init()

    entity.suma = new Cuenta()

    entity.saldo= 0

    list= new HashMap<String,DefaultTreeNode>()
  }

  public List findLsEntity() {

    lsEntity= find(Cuenta,'order by id')

    buildTree(); return lsEntity
  }

  public void buildTree() {

    root= new DefaultTreeNode('Root',null)

    list= new HashMap<String,DefaultTreeNode>()


    for(x in lsEntity) { def id = x.id + ''

      //From level 3 the code is of length 2

      def tam= id.length()

      def aux= tam < 6? 1 : 2

      def end= (tam-aux) > 0? (tam-aux) : 0


      def parentId= id.substring(0,end)

      def parent= list[parentId]

          parent= parent != null? parent : root


      list.put(id, new DefaultTreeNode(x, parent))

      /*if(node.data.nivel < 2) node.expanded= true */}
  }

  public void onNodeSelect(NodeSelectEvent event) {

    form= true; editEntity(selectedNode.data.id)
  }

  public void editEntity(Object id) {

    entity= get(Cuenta.class, id)

    //list[entity.id].selected = true


    for(int i= entity.id.length()-2; i > 2; i=i-2)

    list[entity.id.substring(0,i)]?.expanded= true
  }

  public boolean mergeEntity(Object entity) {

    buildNivel(); return merge(entity) != null
  }

  public void buildNivel() {

    if(entity.nivel != null) return

    def tam= entity.codigo.length()

    entity.nivel= tam < 4? tam : (tam+3)/2
  }

  public List complete(String value) { return completeLike(Cuenta,'tipo= 1 and nombre',value) }

  public Converter getConverter() { return converterLike(Cuenta) }
}
